<?php

namespace app\site\controller\site;


use app\common\exception\MiException;
use app\common\validate\site\UserValidate;
use app\model\site\User;
use app\model\site\UserBalanceLog;
use app\model\site\UserPointsLog;
use app\model\store\DistRewardLog;
use app\Request;
use app\site\controller\AController;
use app\site\controller\traits\CurdTrait;
use app\site\service\site\UserService;
use app\site\service\SiteAuthService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;


class UserController extends AController
{

    /**
     * @throws DbException|MiException
     */
    public function index(){
        $where = [];
        $key = $this->param('where.key');
        if ($key) $where[] = ['id|nickname|mobile', 'like', '%'.$key.'%'];
        return $this->reqSer->setService(UserService::instance()->setWhere($where))->setPaginate()->getResponse();
    }

    /**
     * 获取不分页的列表
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function select(){
        $ids = $this->param('user_ids', '');
        $limit = $this->param('limit', 0);
        $where = [];
        if ($ids) $where[] = ['id', 'in', $ids];

        $ser = UserService::instance()
            ->setLimit($limit)
            ->setWhere($where);
        return $this->reqSer->setService($ser)->setSelect()->getResponse();
    }


    /**
     * @throws MiException
     */
    public function add(): \think\response\Json
    {

        $post = $this->post();
        $post['register_platform'] = 'admin';   // 后台添加
        $post['site_id'] = SiteAuthService::instance()->getSiteId();
        // 验证数据
        validate(UserValidate::class)->scene('add')->check($post);
        UserService::instance()->create($post);
        return jsonSuccess();
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function edit(Request $request){
        if($request->isPost()){
            $post = $this->post();
            // 验证数据
            validate(UserValidate::class)->scene('edit')->check($post);
            UserService::instance()->update($post, ['id' => $post['id']]);
            return jsonSuccess();
        }else{
            return $this->reqSer->setService(UserService::instance())->setFind()->getResponse();
        }
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function del(){
        return $this->reqSer->setService(UserService::instance())->delete()->getResponse();
    }

    /*
     * 调整账户金额数据
     */
    /**
     * @throws MiException
     */
    public function  setAccount(): \think\response\Json
    {
        $handle = $this->post('handle');
        $amount = $this->post('amount');
        $model = $this->post('model');
        $userId = $this->post('user_id');
        $adminNote = $this->post('note', '');
        $siteId = SiteAuthService::instance()->getSiteId();
        $user=null;

        if (!$handle || !$amount || !$userId || !$model) throw new MiException(PARAM_ERROR);
        if ($model == 'balance'){
            $user = User::where('id', $userId)->$handle('balance', $amount)->update();
            // 创建余额记录
            UserBalanceLog::create([
                'site_id' => $siteId,
                'user_id' => $userId,
                'amount' => $handle=='inc' ? $amount : $amount * -1,
                'rel_model' => 'site_user',
                'rel_id' => SiteAuthService::instance()->getLoginId(),
                'change_type' => 1,
                'note' => '平台调整',
                'admin_note' => $adminNote,
            ]);

        }else if ($model == 'points'){
            $user = User::where('id', $userId)->$handle('points', $amount)->update();
            // 创建积分记录
            UserPointsLog::create([
                'site_id' => $siteId,
                'user_id' => $userId,
                'amount' => $handle=='inc' ? $amount : $amount * -1,    // 数量
                'rel_model' => 'site_user',
                'rel_id' => SiteAuthService::instance()->getLoginId(),
                'change_type' => 1,
                'note' => '平台调整',
                'admin_note' => $adminNote,
            ]);
        }else if ($model == 'reward'){
            $user = User::where('id', $userId)->$handle('reward', $amount)->update();
            // 创建积分记录
            DistRewardLog::create([
                'site_id' => $siteId,
                'user_id' => $userId,
                'amount' => $handle=='inc' ? $amount : $amount * -1,    // 数量
                'rel_model' => 'site_user',
                'rel_id' => SiteAuthService::instance()->getLoginId(),
                'reward_type' => 4,
                'note' => '平台调整',
                'admin_note' => $adminNote,
                'status' => 1,
            ]);
        }

        return jsonSuccess([
            'user' => $user
        ]);
    }

}
